import _ from 'lodash';
import dayjs from 'dayjs';
import { DROPDOWN, DATEPICKER, DATEFORMAT, DEFAULTATTACHMENTURL } from './constant';

export const transformArray = (arr) => {
  if (!arr) {
    return
  }
  return arr.map(item => ({ label: item, value: item }));
}

export const download = (res) => {
  if (!res?.headers) {
    return
  }
  const url = window.URL.createObjectURL(new Blob([res?.data], { type: "application/vnd.ms-excel;charset=utf-8" }));
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', decodeURI(res?.headers['content-disposition']?.split(';')[1]?.split('=')[1]));
  link.click();
}

export const getUserData = () => {
  const userInfo = localStorage.getItem('userAccess');
  const userInfoJson = userInfo && JSON.parse(userInfo);
  const currentUser = userInfoJson ?? {};
  return currentUser;
}

export const getUserName = () => {
  const currentUser = getUserData();
  return currentUser['userEmail'] || '';
}

export const getUserAccessData = () => {
  const userAccess = JSON.parse(localStorage.getItem('userAccess'));
  const userGroupData = userAccess?.userGroup || [];
  return userGroupData;
}
// 格式化下拉框列表
export const formatSelectOptions = (list = [], valueKey = "", labelKey = "") => {
  if (!valueKey && !labelKey && (list[0] && typeof list[0] === 'object')) {
    throw new Error(`Missing the valuekey and labelKey to be specified.`)
  };
  let newValue = [];
  list.map((item) => {
    newValue.push({
      value: valueKey && item?.[valueKey] ? item?.[valueKey] : item,
      label: labelKey && item?.[labelKey] ? item?.[labelKey] : item,
    })
  })
  return newValue;
};

export const convertNullToStringOrArr = (data, toNullArr, transformNumToStr) => {
  if ((data === undefined || data === null) && toNullArr) {
    return [];
  } else if (data === undefined || data === null) {
    return '';
  } else if (transformNumToStr) {
    return `${data}`;
  } else {
    return data;
  }
}

export const stringToArrayFn = (str) => {
  if (Array.isArray(str)) { return str };
  if (!str) { return [] }
  const arr = str.split(",");
  return arr;
}

export const isJSON = (str) => {
  if (typeof str == 'string') {
    try {
      const obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.warn(`isJSON Illegal parameters : ${str}`);
      return false;
    };
  }
}

export const debounce = (func, wait) => {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      func.apply(context, args);
    }, wait);
  };
}

export const resquestDetialAttachmentFormat = (files) => {
  let fileList = [];
  if (files?.split && files?.split(',')?.[0]) {
    fileList = files?.split(',')?.map((item) => {
      return {
        name: item,
        status: 'done',
        url: item,
        attachmentUrl: item,
      }
    }) || [];
  };
  return fileList;
}
// 格式化附件列表
export const resquestDetialAttachmentListFormat = (files) => {
  let fileList = [];
  if (_.isArray(files)) {
    fileList = files?.map((item, index) => {
      return {
        ...item,
        uid: item?.attachmentInfoId,
        name: item?.attachmentName,
        status: 'done',
        url: `${DEFAULTATTACHMENTURL}${item?.attachmentUrl}`,
      }
    }) || [];
  }
  return fileList;
}
// 每个一级/二级页面 pageView权限
export const getPageOperationPermission = (childItem, operationType) => {
  const viewPremission = childItem?.permissList?.filter(val => val.permissName === operationType)?.[0];
  return viewPremission || {};
};

export const hasCampAdminRole = (viewPremission) => {
  // 有指定moduleName时需校验是否具有对应module的权限
  let result = null;
  const userCampData = viewPremission?.userCampRole?.length > 0 && _.find(getUserAccessData(), ((item) => {
    if (viewPremission?.userCampRole?.length === 1 && viewPremission?.userCampRole?.[0] === '*-Admin') {
      return item.userCampRole?.includes('-Admin');
    } else {
      return viewPremission?.userCampRole?.includes(item.userCampRole)
    }
  }));
  if (viewPremission?.moduleName?.length > 0) {
    result = viewPremission?.moduleName?.includes(userCampData?.buRole?.[0]?.module);
  } else {
    result = !_.isEmpty(userCampData);
  };
  return result;
};

export const hasBuRole = (viewPremission) => {
  const viewerRolesAll = _.find(getUserAccessData(), ((item) => { return !item.userCampRole.includes(viewPremission?.userCampRole) }))?.buRole;
  let viewerModuleRoles = [];
  //有指定moduleName时需校验是否具有对应module的权限
  if (viewPremission?.moduleName?.length > 0) {
    viewerModuleRoles = viewerRolesAll?.filter(item => viewPremission?.moduleName?.includes(item.module));
  } else {
    viewerModuleRoles = viewerRolesAll;
  };
  const viewerRoles = viewerModuleRoles?.reduce((result, item) => {
    result?.push(...item.role);
    return result;
  }, []);
  const userModuleRole = _.intersection(viewPremission?.buRole, viewerRoles);
  const result = _.intersection(viewPremission?.buRole, userModuleRole)?.length > 0;
  return result;
};

// 根据url获取权限列表
export const getPagePermissionByUrl = (data, value) => {
  let result = null;
  for (let item of data) {
    if (item?.url === value) {
      result = item;
      break;
    } else {
      result = item?.children?.filter(chilitem => chilitem?.url === value)?.[0];
      if (result) {
        break;
      };
    }
  };
  return result;
};

// 百分比计算
export const calculatePercentage = (value, min, max) => {
  if (!value && !min && !max && !isNaN(value) && !isNaN(min) && !isNaN(max)) {
    throw new Error(`Please check if the parameters are correct.`)
  };
  return (((value - min) / (max - min)) * 100)?.toFixed(2);
};

// 格式化request item 数据
export const formatRequestItemData = (data) => {
  _.forIn(data, (value, key) => {
    if (value.fieldType === DATEPICKER) {
      data[key].fieldValue = data[key]?.fieldValue ? dayjs(data[key].fieldValue, DATEFORMAT) : null;
    } else if (value.fieldType === DROPDOWN) {
      data[key].fieldValue = data[key]?.fieldValue !== '' && data[key]?.fieldValue?.split(',') || [];
    }
  });
  return data;
};